﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using SPWP.OpinionPoll;
using System.Collections.Generic;
using System.Text;

namespace SPWP.OpinionPoll.PollAdmin
{
    public partial class OpinionPollAdminUserControl : UserControl
    {
        static private List<PollAnswer> answerView;

        #region Web Form
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            { 
                SetControlCaption();
                SetMenuForm();
                GetAllPoll();

                idPoll.Value = "0";
            }
        }

        private void SetControlCaption()
        {
            lblViewHeader.Text = "Add / Edit Poll";

            lblPollTitle.Text = "Poll";
            lblExpireOn.Text = "Expire on";
            lblPublished.Text = "Active";
            lblMultipleSelection.Text = "Allow Multiple Selection";
            //lblCategory.Text = ControlText.category;

            rfvTitle.ErrorMessage = "Poll question is required";
            cmpValDate.ErrorMessage = "Expire date is required";
            //rfvCategory.ErrorMessage = ControlText.categoryValidate;

            //grdPoll.Columns[0].HeaderText = ControlText.pollID;
            grdPoll.Columns[1].HeaderText = "Poll Question";
            grdPoll.Columns[2].HeaderText = "Expire On";
            //grdPoll.Columns[3].HeaderText = ControlText.createdBy;
            grdPoll.Columns[3].HeaderText = "Created On";
            //grdPoll.Columns[5].HeaderText = ControlText.modifiedBy;
            //grdPoll.Columns[6].HeaderText = ControlText.modifiedDate;
            grdPoll.Columns[4].HeaderText = "Is Active";
            grdPoll.Columns[5].HeaderText = "Action";

            //lstCategory.Items.Add(new ListItem { Text = ControlText.chooseOne, Value = "0" });
            //lstCategory.Items.Add(new ListItem { Text = "Test Category", Value = "Test Category" });
            //lstCategory.Items.Add(new ListItem { Text = "Services", Value = "Services" });

            cmdAddPoll.Text = "Add Poll";

            lnkCloseAnswer.Text = "Close Option List";
            lnkAddAnswer.Text = "Add Option";

            lblAddEditAnswer.Text = "Add / Edit Option";

            fields.Visible = false;
            addeditanswer.Visible = false;

            lnkCloseVote.Text = "Close Vote List";
            lblViewVote.Text = "View / Delete Vote";

            viewvote.Visible = false;
        }

        private void SetMenuForm()
        {
            MenuItem obj = new MenuItem("<img src='" + "/_layouts/images/OpinionPoll/" + "save.png' width='17' height='17' style='vertical-align: text-bottom; border-width: 0;' />&nbsp;" + "Save", "save");
            mnuAddEdit.Items.Add(obj);

            MenuItem obj2 = new MenuItem("<img src='" + "/_layouts/images/OpinionPoll/" + "cancel.png' width='17' height='17' style='vertical-align: text-bottom; border-width: 0;' />&nbsp;" + "Cancel", "cancel");
            mnuAddEdit.Items.Add(obj2);           
            
        }

        public static void ShowNoResultFound<T>(List<T> source, GridView gv) where T : new()
        {
            if (source == null)
                return;

            source.Add(new T());
            gv.DataSource = source;
            gv.DataBind();

            // Get the total number of columns in the GridView to know what the Column Span should be       
            int columnsCount = gv.Columns.Count;
            gv.Rows[0].Cells.Clear();// clear all the cells in the row       
            gv.Rows[0].Cells.Add(new TableCell()); //add a new blank cell       
            gv.Rows[0].Cells[0].ColumnSpan = columnsCount; //set the column span to the new added cell
 
            ////gv.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;       
            ////gv.Rows[0].Cells[0].ForeColor = System.Drawing.Color.Red;       
            ////gv.Rows[0].Cells[0].Font.Bold = true;
     
            //gv.Rows[0].Cells[0].CssClass = "EmptyDataRowStyle";

            //set No Results found to the new added cell       
            gv.Rows[0].Cells[0].Text = "No record found";

        }

        #endregion

        #region Poll Operation

        private void GetAllPoll()
        {
            QueryList query = new QueryList("Polls");
            List<PollMaster> allPolls = new List<PollMaster>();

            allPolls = query.ViewAllPoll();

            foreach (PollMaster item in allPolls)
            {
                if (item.IsActive.Equals("Yes"))
                {
                    item.IsActive = "<img src='" + "/_layouts/images/OpinionPoll/" + "publish.png' width='17' height='17' alt='" + "Active" + "' title='" + "Active" + "' style='vertical-align: text-bottom; border-width: 0;' />";
                }
                else
                {
                    item.IsActive = String.Empty;
                }
            }

            grdPoll.DataSource = allPolls;
            grdPoll.DataBind();
        }

        protected void grdPoll_DataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ImageButton revVote = e.Row.FindControl("lnkReviewVote") as ImageButton;
                if (revVote != null)
                {
                    revVote.ImageUrl = "/_layouts/images/OpinionPoll/" + "reviewvote.png";
                    revVote.AlternateText = "Review Vote";
                    revVote.Attributes.Add("title", "Review Vote");
                }

                ImageButton lnkManAns = e.Row.FindControl("lnkManageAnswers") as ImageButton;
                if (lnkManAns != null)
                {
                    lnkManAns.ImageUrl = "/_layouts/images/OpinionPoll/" + "manageanswer.png";
                    lnkManAns.AlternateText = "Manage Option";
                    lnkManAns.Attributes.Add("title", "Manage Option");
                }

                ImageButton lnkEd = e.Row.FindControl("lnkEdit") as ImageButton;
                if (lnkEd != null)
                {
                    lnkEd.ImageUrl = "/_layouts/images/OpinionPoll/" + "edit.png";
                    lnkEd.AlternateText = "Edit Poll";
                    lnkEd.Attributes.Add("title", "Edit Poll");
                }

                ImageButton lnkRemove = e.Row.FindControl("lnkRemove") as ImageButton;
                if (lnkRemove != null)
                {
                    lnkRemove.ImageUrl = "/_layouts/images/OpinionPoll/" + "delete.png";
                    lnkRemove.AlternateText = "Delete Poll";
                    lnkRemove.Attributes.Add("title", "Delete Poll");
                }

                Label lblPublish = e.Row.FindControl("publish") as Label;
                bool isPublish = Convert.ToBoolean(lblPublish.Text);

                if (!isPublish)
                {
                    ImageButton lnkPublishResult = e.Row.FindControl("lnkPublishResult") as ImageButton;
                    if (lnkPublishResult != null)
                    {
                        lnkPublishResult.ImageUrl = "/_layouts/images/OpinionPoll/" + "chart-bar-icon.png";
                        lnkPublishResult.AlternateText = "Publish Result";
                        lnkPublishResult.Attributes.Add("title", "Publish Result");
                        lnkPublishResult.Visible = true;
                    }
                }
                else
                { 
                    ImageButton lnkUnpublishResult = e.Row.FindControl("lnkUnpublishResult") as ImageButton;
                    if (lnkUnpublishResult != null)
                    {
                        lnkUnpublishResult.ImageUrl = "/_layouts/images/OpinionPoll/" + "chart-bar-delete-icon.png";
                        lnkUnpublishResult.AlternateText = "Unpublish Result";
                        lnkUnpublishResult.Attributes.Add("title", "Unpublish Result");
                        lnkUnpublishResult.Visible = true;
                    }
                }
            }

            if (e.Row.RowType == DataControlRowType.Header)
            {
                //grdPoll.Columns[0].HeaderText = ControlText.pollID;
                grdPoll.Columns[1].HeaderText = "Poll Question";
                grdPoll.Columns[2].HeaderText = "Expire On";
                //grdPoll.Columns[3].HeaderText = ControlText.createdBy;
                grdPoll.Columns[3].HeaderText = "Created On";
                //grdPoll.Columns[5].HeaderText = ControlText.modifiedBy;
                //grdPoll.Columns[6].HeaderText = ControlText.modifiedDate;
                grdPoll.Columns[4].HeaderText = "Is Active";
                grdPoll.Columns[5].HeaderText = "Action";
            }
        }

        protected void PublishResult(object sender, EventArgs e)
        {
            ImageButton lnkPublish = (ImageButton)sender;
            QueryList editQuery = new QueryList("Polls");

            string message = editQuery.PublishPoll(Int32.Parse(lnkPublish.CommandArgument));

            lblMessage.Text = "<img src='" + "/_layouts/images/OpinionPoll/" + "status-icon.png' width='17' height='17' style='vertical-align: text-bottom; border-width: 0;' />&nbsp;" + message;
            GetAllPoll();
        }

        protected void cmdAddPoll_Click(object sender, EventArgs e)
        {
            fields.Visible = true;
            cmdAddPoll.Visible = false;

            ((TextBox)(dtExpire.Controls[0])).Attributes.Add("readonly", "readOnly");
            dtExpire.IsRequiredField = true;
            dtExpire.MinDate = System.DateTime.Today;

            fields.Attributes.Add("class", "viewdiv");
        }

        protected void EditPoll(object sender, EventArgs e)
        {
            ImageButton lnkEdit = (ImageButton)sender;
            QueryList editQuery = new QueryList("Polls");

            try
            {
                PollMaster editPoll = editQuery.ViewPollByID(Int32.Parse(lnkEdit.CommandArgument));

                idPoll.Value = lnkEdit.CommandArgument;
                fields.Visible = true;

                // populate form
                txtPollTitle.Text = editPoll.PollTitle;
                dtExpire.SelectedDate = editPoll.ExpireOn;
                chkActive.Checked = (editPoll.IsActive == "Yes") ? true : false;
                chkMultiSelect.Checked = (editPoll.MultiChoice == "Yes") ? true : false;

                ((TextBox)(dtExpire.Controls[0])).Attributes.Add("readonly", "readOnly");
                dtExpire.IsRequiredField = true;
                dtExpire.MinDate = System.DateTime.Today;
                cmdAddPoll.Visible = false;

                char[] separator = { '#' };

                //if (editPoll.Category != String.Empty)
                //{
                //    string category = editPoll.Category.TrimStart(separator);
                //    lstCategory.SelectedValue = category;
                //}

            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message;
            }
        }

        protected void DeletePoll(object sender, EventArgs e)
        {
            ImageButton lnkRemove = (ImageButton)sender;
            QueryList delQuery = new QueryList("Polls");
            string message = delQuery.DeletePoll(Int32.Parse(lnkRemove.CommandArgument));

            lblMessage.Text = "<img src='" + "/_layouts/images/OpinionPoll/" + "status-icon.png' width='17' height='17' style='vertical-align: text-bottom; border-width: 0;' />&nbsp;" + message;
            GetAllPoll();
        }

        protected void mnuAddEdit_MenuItemClick(object sender, EventArgs e)
        {
            if (String.Compare(mnuAddEdit.SelectedValue, "save", true) == 0)
            {
                Page.Validate("addedit");

                if ((Page.IsValid) && (!dtExpire.IsDateEmpty))
                {
                    PollMaster newPoll = new PollMaster();

                    newPoll.PollID = Convert.ToInt32(idPoll.Value);

                    newPoll.PollTitle = txtPollTitle.Text.Trim();
                    newPoll.ExpireOn = dtExpire.SelectedDate;
                    newPoll.SortOrder = "As Written";

                    if (chkActive.Checked)
                        newPoll.IsActive = "Yes";
                    else
                        newPoll.IsActive = "No";

                    newPoll.AnonymousVote = "Yes";

                    if (chkMultiSelect.Checked)
                    {
                        newPoll.MultiChoice = "Yes";
                    }
                    else
                    {
                        newPoll.MultiChoice = "No";
                    }

                    //if (null != lstCategory.SelectedValue)
                    //    newPoll.Category = lstCategory.SelectedItem.Text;

                    string message = String.Empty;

                    if (idPoll.Value == "0") // it's a new poll
                    {
                        QueryList addQuery = new QueryList("Polls");
                        message = addQuery.AddPoll(newPoll);
                    }
                    else
                    {
                        QueryList updateQuery = new QueryList("Polls");
                        message = updateQuery.UpdatePoll(newPoll);
                    }

                    lblMessage.Text = "<img src='" + "/_layouts/images/OpinionPoll/" + "status-icon.png' width='17' height='17' style='vertical-align: text-bottom; border-width: 0;' />&nbsp;" + message;

                    GetAllPoll();

                    fields.Visible = false;
                    cmdAddPoll.Visible = true;

                }
                else
                {
                    dtExpire.MinDate = DateTime.Today;
                }
            }
            else
            {
                txtPollTitle.Text = String.Empty;
                dtExpire.ClearSelection();
                chkActive.Checked = false;
                chkMultiSelect.Checked = false;

                fields.Visible = false;
                cmdAddPoll.Visible = true;
            }

            idPoll.Value = "0";
            dtExpire.IsRequiredField = false;
            fields.Attributes.Remove("class");
        }

        #endregion

        #region Poll Answer Operation

        protected void grdAnswer_DataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                grdAnswer.Columns[1].HeaderText = "Option";
                grdAnswer.Columns[2].HeaderText = "Display Order";
                grdAnswer.Columns[3].HeaderText = "Action";
            }
        }

        protected void EditAnswer(object sender, GridViewEditEventArgs e)
        {
            grdAnswer.EditIndex = e.NewEditIndex;

            grdAnswer.DataSource = answerView;
            grdAnswer.DataBind();

        }

        protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
        {
            grdAnswer.EditIndex = -1;

            grdAnswer.DataSource = answerView;
            grdAnswer.DataBind();
        }

        protected void UpdateData(object sender, GridViewUpdateEventArgs e)
        {
            Page.Validate("AddUpdate");

            if (Page.IsValid)
            {
                Label lblPoll = (Label)grdAnswer.Rows[e.RowIndex].FindControl("lblPollID");
                Label lblID = (Label)grdAnswer.Rows[e.RowIndex].FindControl("lblAnswerID");
                TextBox txtTitle = (TextBox)grdAnswer.Rows[e.RowIndex].FindControl("txtAnswerTitle");
                TextBox txtSortOrder = (TextBox)grdAnswer.Rows[e.RowIndex].FindControl("txtSortOrder");

                int pollid = Convert.ToInt32(lblPoll.Text);
                int answerid = Convert.ToInt32(lblID.Text);
                string answer = txtTitle.Text.Trim();
                int sortOrder = Convert.ToInt32(txtSortOrder.Text.Trim());
            
                PollAnswer newPoll = new PollAnswer();

                newPoll.PollID = Convert.ToInt32(pollid);
                newPoll.ID = Convert.ToInt32(answerid);
                newPoll.Answer = answer;
                newPoll.SortOrder = sortOrder;

                string message = String.Empty;

                if (newPoll.ID.Equals(0)) // it's a new poll answer
                {
                    QueryAnswer addQuery = new QueryAnswer("Poll Answers");
                    message = addQuery.AddAnswer(newPoll);
                }
                else
                {
                    QueryAnswer addQuery = new QueryAnswer("Poll Answers");
                    message = addQuery.UpdateAnswer(newPoll);
                }

                lblMessageAnswer.Text = "<img src='" + "/_layouts/images/OpinionPoll/" + "status-icon.png' width='17' height='17' style='vertical-align: text-bottom; border-width: 0;' />&nbsp;" + message;
                grdAnswer.EditIndex = -1;

                PopulatePollAnswer(Convert.ToInt32(idPollAnswer.Value));

            }
        }

        protected void DeleteData(object sender, EventArgs e)
        {
            LinkButton lnkRemove = (LinkButton)sender;
            QueryAnswer delQuery = new QueryAnswer("Poll Answers");
            string message = delQuery.DeleteAnswer(Int32.Parse(lnkRemove.CommandArgument));

            lblMessageAnswer.Text = "<img src='" + "/_layouts/images/OpinionPoll/" + "status-icon.png' width='17' height='17' style='vertical-align: text-bottom; border-width: 0;' />&nbsp;" + message;
            PopulatePollAnswer(Convert.ToInt32(idPollAnswer.Value));
        }

        protected void AddData(object sender, EventArgs e)
        {
            Page.Validate("AddUpdate");

            if (Page.IsValid)
            {
                TextBox txtTitle = (TextBox)grdAnswer.FooterRow.FindControl("txtAnswerTitle");
                TextBox txtSortOrder = (TextBox)grdAnswer.FooterRow.FindControl("txtSortOrder");

                int pollid = Convert.ToInt32(idPollAnswer.Value);
                string answer = txtTitle.Text.Trim();
                int sortOrder = Convert.ToInt32(txtSortOrder.Text.Trim());

                PollAnswer newPoll = new PollAnswer();

                newPoll.PollID = Convert.ToInt32(pollid);
                newPoll.Answer = answer;
                newPoll.SortOrder = sortOrder;

                string message = String.Empty;

                if (newPoll.ID.Equals(0)) // it's a new poll answer
                {
                    QueryAnswer addQuery = new QueryAnswer("Poll Answers");
                    message = addQuery.AddAnswer(newPoll);
                }
                else
                {
                    QueryAnswer addQuery = new QueryAnswer("Poll Answers");
                    message = addQuery.UpdateAnswer(newPoll);
                }

                lblMessageAnswer.Text = "<img src='" + "/_layouts/images/OpinionPoll/" + "status-icon.png' width='17' height='17' style='vertical-align: text-bottom; border-width: 0;' />&nbsp;" + message;
                grdAnswer.EditIndex = -1;

                PopulatePollAnswer(Convert.ToInt32(idPollAnswer.Value));

            }
        }

        protected void lnkAddAnswer_Click(object sender, EventArgs e)
        {
            grdAnswer.ShowFooter = true;
            ((TextBox)grdAnswer.FooterRow.FindControl("txtAnswerTitle")).Attributes.Add("placeholder", "Enter option here");
            ((TextBox)grdAnswer.FooterRow.FindControl("txtSortOrder")).Attributes.Add("placeholder", "e.g. 1");

            PopulatePollAnswer(Convert.ToInt32(idPollAnswer.Value));

        }

        protected void lnkCloseAnswer_Click(object sender, EventArgs e)
        {
            addeditanswer.Visible = false;
            idPollAnswer.Value = "0";
        }

        protected void CancelAdd(object sender, EventArgs e)
        {
            grdAnswer.ShowFooter = false;
            PopulatePollAnswer(Convert.ToInt32(idPollAnswer.Value));

        }

        private void PopulatePollAnswer(int pollIDSearch)
        {
            QueryAnswer query = new QueryAnswer("Poll Answers");
            List<PollAnswer> allAnswer = new List<PollAnswer>();

            allAnswer = query.ViewPollAnswerByID(pollIDSearch);

            grdAnswer.Columns[1].HeaderText = "Option";
            grdAnswer.Columns[2].HeaderText = "Display Order";
            grdAnswer.Columns[3].HeaderText = "Action";

            grdAnswer.DataSource = allAnswer;
            grdAnswer.DataBind();

            answerView = allAnswer;

            if (allAnswer.Count == 0)
            {
                ShowNoResultFound<PollAnswer>(new List<PollAnswer>(), grdAnswer);
            }
            
        }

        protected void ManageAnswer(object sender, EventArgs e)
        {
            ImageButton btn = sender as ImageButton;
            int pollID = Convert.ToInt32(btn.CommandArgument);

            grdAnswer.Columns[1].HeaderText = "Option";
            grdAnswer.Columns[2].HeaderText = "Display Order";
            grdAnswer.Columns[3].HeaderText = "Action";

            PopulatePollAnswer(pollID);

            lblMessageAnswer.Text = string.Empty;
            addeditanswer.Visible = true;

            idPollAnswer.Value = pollID.ToString();
        }

        #endregion

        #region Review Vote
        
        protected void ReviewVote(object sender, EventArgs e)
        {
            ImageButton lnk = sender as ImageButton;

            int pollID = Convert.ToInt32(lnk.CommandArgument);
            lblMessageVote.Text = String.Empty;

            GetAllVote(pollID);
            viewvote.Visible = true;

            pollIDanswer.Value = pollID.ToString();

            lnkCloseVote.Visible = true;
        }

        protected void grdVote_DataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                grdVote.Columns[1].HeaderText = "Voted On";
                grdVote.Columns[2].HeaderText = "IP Address";
                grdVote.Columns[3].HeaderText = "Option Picked";
                grdVote.Columns[4].HeaderText = "Action";
            }
        }

        private void GetAllVote(int pollID)
        {
            List<PollVote> voteList = new List<PollVote>();
            PollVoteList objQuery = new PollVoteList();

            voteList = objQuery.GetResult(pollID);

            grdVote.Columns[1].HeaderText = "Voted On";
            grdVote.Columns[2].HeaderText = "IP Address";
            grdVote.Columns[3].HeaderText = "Option Picked";
            grdVote.Columns[4].HeaderText = "Action";

            grdVote.DataSource = voteList;
            grdVote.DataBind();

        }

        protected void lnkCloseVote_Click(object sender, EventArgs e)
        {
            viewvote.Visible = false;
            lnkCloseVote.Visible = false;
        }

        protected void DeleteVote(object sender, EventArgs e)
        {
            LinkButton lnkRemove = (LinkButton)sender;
            PollVoteList objQuery = new PollVoteList();

            int pollID = Convert.ToInt32(pollIDanswer.Value);

            string message = objQuery.DeleteVote(Int32.Parse(lnkRemove.CommandArgument), pollID);

            lblMessageVote.Text = "<img src='" + "/_layouts/images/OpinionPoll/" + "status-icon.png' width='17' height='17' style='vertical-align: text-bottom; border-width: 0;' />&nbsp;" + message;

            GetAllVote(pollID);
        }

        #endregion
        
    }
}
